package com.zyn.rsgl.controller;

import com.zyn.rsgl.pojo.User;
import com.zyn.rsgl.service.UserService;
import com.zyn.rsgl.utils.commonResult.R;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author zcs
 * @since 2025-03-10
 */
@RestController
@RequestMapping("/rsgl/user")
public class UserController {
    @Resource
    private UserService userService;

    // 获取所有用户信息
    @GetMapping("/list")
    public R list(
            @RequestParam(required = false) Integer pageNum,
            @RequestParam(required = false) Integer pageSize,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String department,
            @RequestParam(required = false) String contactInformation) {
        return userService.listPage(pageNum, pageSize, username, name, department, contactInformation);
    }

    // 获取单个用户信息
    @GetMapping("/get/{userId}")
    public R get(@PathVariable("userId") String userId) {
        User user = userService.getById(userId);
        if (user != null) {
            return R.ok(user);
        }
        return R.fail("用户不存在");
    }

    // 添加用户信息
    @PostMapping("/add")
    public R add(@RequestBody User user) {
        // 判断是否存在
        if (userService.getById(user.getId()) != null) {
            return R.fail("用户已存在");
        }
        boolean isSuccess = userService.save(user);
        if (isSuccess) {
            return R.ok("添加成功");
        }
        return R.fail("添加失败");
    }

    // 修改用户信息
    @PutMapping("/update")
    public R update(@RequestBody User user) {
        boolean isSuccess = userService.updateById(user);
        if (isSuccess) {
            return R.ok("修改成功");
        }
        return R.fail("修改失败");
    }

    // 删除用户信息
    @DeleteMapping("/delete/{userId}")
    public R delete(@PathVariable("userId") String userId) {
        boolean isSuccess = userService.removeById(userId);
        if (isSuccess) {
            return R.ok("删除成功");
        }
        return R.fail("删除失败");
    }

    // 登录
    @PostMapping("/login")
    public R login(@RequestBody User user) {
        return userService.login(user);
    }
}
